home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 12169 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.1 KB  |  64 lines

  1. Path: ix.netcom.com!netnews
  2. From: jlilley@ix.netcom.com (John Lilley)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Casting pointer to member function to pointer to function
  5. Date: 18 Mar 1996 18:03:06 GMT
  6. Organization: Netcom
  7. Message-ID: <4ik8gq$14k@reader2.ix.netcom.com>
  8. References: <314CD34A.7DBB@world.std.com>
  9. NNTP-Posting-Host: den-co8-14.ix.netcom.com
  10. Mime-Version: 1.0
  11. Content-Type: Text/Plain; charset=US-ASCII
  12. X-NETCOM-Date: Mon Mar 18 10:03:06 AM PST 1996
  13. X-Newsreader: WinVN 0.99.7
  14.  
  15. In article <314CD34A.7DBB@world.std.com>, slide@world.std.com says...
  16. >
  17. >Hi all,
  18. >
  19. >I can't seem to get this to work and can't figure if it's even legal.  I 
  20. >have a global function that takes as an argument a pointer to function. 
  21. >The pointer to function is defined as 
  22. >
  23. >long (__stdcall *)(void *,unsigned int,unsigned int,long)
  24. >
  25. >I would like to pass a function that is a member of a class called CGWnd 
  26. >to this function which would be defined as:
  27. >
  28. >long (__stdcall CGWnd::*)(void *,unsigned int,unsigned int,long)
  29. >
  30. >I've tried casting but but MSVC++ gives me an error that effectively 
  31. >says I can't cast away the function's class membership.  Anyone know if 
  32. >there is a way around this?
  33.  
  34. Yes, this is illegal.  Member functions have an implicit "this"
  35. argument,  You should not even attempt to write a function that
  36. emulates the "this" argument because compilers are free to choose
  37. a different calling convention for member functions.
  38.  
  39. Instead, write a wrapper.  This is ugly because you cannot associate
  40. the wrapper with a particular "A", so you must use a global "A".
  41. class A {
  42.     long memberFunction(void* unsigned int, unsigned int, long);
  43. };
  44.  
  45. // squirrel away some global A where you can get it...
  46. A *globalA:
  47. long wrapperFunction(void* vp, unsigned int ui1, unsigned int ui2, long l)
  48. {
  49.    return globalA->memberFunction(vp, ui1, ui2, l);
  50. }
  51.  
  52. However, in many cases of callback functions like this,
  53. the (void*) is a pointer to any data you want so you could use
  54. the "A" there and make it a lot cleaner.
  55.  
  56. long wrapperFunction(void* vp, unsigned int ui1, unsigned int ui2, long l)
  57. {
  58.    A* ap = (A*)vp;
  59.    return ap->memberFunction(vp, ui1, ui2, l);
  60. }
  61.  
  62. john lilley
  63.  
  64.